import {
	createRepairServiceOrderWithPayment,
	getRepairServiceOrderPaymentStatus
} from '@/api/order.js';
import storage from '@/utils/storage.js';

/**
 * 家庭服务订单支付处理类
 */
class RepairServicePayment {
	constructor() {
		this.pollingIntervals = new Map(); // 存储轮询定时器
		this.maxPollingAttempts = 20; // 最大轮询次数
		this.pollingInterval = 3000; // 轮询间隔（毫秒）
	}

	/**
	 * 获取用户openid
	 */
	getUserOpenid() {
		const userInfo = storage.getUserInfo();
		return userInfo?.openid || '';
	}

	/**
	 * 创建订单并获取支付参数
	 * @param {Object} orderData 订单数据
	 * @param {string} orderData.typeId 服务类型ID
	 * @param {string} orderData.dateTime 预约时间
	 * @param {string} orderData.address 服务地址
	 * @param {string} orderData.remark 备注
	 */
	async createOrderAndGetPayment(orderData) {
		try {
			const openid = this.getUserOpenid();
			if (!openid) {
				throw new Error('用户未登录或openid获取失败');
			}

			// 验证订单数据
			if (!orderData.typeId) {
				throw new Error('服务类型ID不能为空');
			}
			if (!orderData.dateTime) {
				throw new Error('预约时间不能为空');
			}
			if (!orderData.address) {
				throw new Error('服务地址不能为空');
			}

			// 获取用户绑定的小区ID
			const userInfo = storage.getUserInfo();
			const communityId = userInfo?.community?._id;

			const params = {
				...orderData,
				payType: 'jsapi',
				openid: openid
			};

			// 如果用户已绑定小区，自动添加communityId
			if (communityId) {
				params.communityId = communityId;
			}

			console.log('创建订单参数:', params);

			const response = await createRepairServiceOrderWithPayment(params);
			
			console.log('创建订单响应:', response);
			
			if (response.data.code === 200) {
				const { order, payParams } = response.data.data;
				
				// 验证支付参数
				if (!payParams) {
					throw new Error('支付参数获取失败');
				}
				
				const requiredParams = ['timeStamp', 'nonceStr', 'package', 'signType', 'paySign'];
				for (const param of requiredParams) {
					if (!payParams[param]) {
						throw new Error(`支付参数缺失: ${param}`);
					}
				}
				
				console.log('支付参数验证通过:', payParams);
				
				return {
					order: order,
					payParams: payParams
				};
			} else {
				throw new Error(response.data.message || '创建订单失败');
			}
		} catch (error) {
			console.error('创建订单失败:', error);
			throw error;
		}
	}

	/**
	 * 调起微信支付
	 * @param {Object} payParams 支付参数
	 */
	callWechatPay(payParams) {
		return new Promise((resolve, reject) => {
			// 再次验证支付参数
			const requiredParams = ['timeStamp', 'nonceStr', 'package', 'signType', 'paySign'];
			for (const param of requiredParams) {
				if (!payParams[param]) {
					reject(new Error(`支付参数缺失: ${param}`));
					return;
				}
			}
			
			console.log('调起微信支付，参数:', payParams);
			
			uni.requestPayment({
				timeStamp: payParams.timeStamp,
				nonceStr: payParams.nonceStr,
				package: payParams.package,
				signType: payParams.signType,
				paySign: payParams.paySign,
				success: (res) => {
					console.log('微信支付成功:', res);
					resolve(res);
				},
				fail: (err) => {
					console.log('微信支付失败:', err);
					let errorMsg = '支付失败';
					
					// 根据不同的错误类型给出具体的错误信息
					if (err.errMsg === 'requestPayment:fail cancel') {
						errorMsg = '用户取消支付';
					} else if (err.errMsg && err.errMsg.includes('timeStamp')) {
						errorMsg = '支付时间戳错误';
					} else if (err.errMsg && err.errMsg.includes('sign')) {
						errorMsg = '支付签名错误';
					} else if (err.errMsg && err.errMsg.includes('package')) {
						errorMsg = '支付包名错误';
					} else if (err.errMsg && err.errMsg.includes('nonceStr')) {
						errorMsg = '随机字符串错误';
					} else if (err.errMsg) {
						errorMsg = `支付失败: ${err.errMsg}`;
					}
					
					reject(new Error(errorMsg));
				}
			});
		});
	}

	/**
	 * 查询支付状态
	 * @param {string} orderId 订单ID
	 */
	async queryPaymentStatus(orderId) {
		try {
			if (!orderId) {
				throw new Error('订单ID不能为空');
			}
			
			console.log('查询支付状态，订单ID:', orderId);
			
			const response = await getRepairServiceOrderPaymentStatus(orderId);
			
			console.log('支付状态查询响应:', response);
			
			if (response.data.code === 200) {
				return response.data.data;
			} else {
				throw new Error(response.data.message || '查询支付状态失败');
			}
		} catch (error) {
			console.error('查询支付状态失败:', error);
			throw error;
		}
	}

	/**
	 * 开始轮询支付状态
	 * @param {string} orderId 订单ID
	 * @param {Function} onSuccess 支付成功回调
	 * @param {Function} onFail 支付失败回调
	 * @param {Function} onTimeout 支付超时回调
	 */
	startPaymentPolling(orderId, onSuccess, onFail, onTimeout) {
		let attempts = 0;
		
		const poll = async () => {
			try {
				attempts++;
				console.log(`第${attempts}次查询支付状态`);
				
				const result = await this.queryPaymentStatus(orderId);
				
				if (result.payStatus === 'paid') {
					// 支付成功
					console.log('支付成功，停止轮询');
					this.stopPolling(orderId);
					onSuccess && onSuccess(orderId, result);
					return;
				} else if (result.payStatus === 'unpaid') {
					// 未支付，继续轮询
					if (attempts < this.maxPollingAttempts) {
						console.log(`支付未完成，${this.pollingInterval}ms后重试`);
						this.pollingIntervals.set(orderId, setTimeout(poll, this.pollingInterval));
					} else {
						// 轮询超时
						console.log('支付状态查询超时');
						this.stopPolling(orderId);
						onTimeout && onTimeout(orderId);
					}
				} else {
					// 其他状态
					console.log(`支付状态异常: ${result.payStatus}`);
					this.stopPolling(orderId);
					onFail && onFail(orderId, new Error(`支付状态异常: ${result.payStatus}`));
				}
			} catch (error) {
				console.error('轮询查询失败:', error);
				if (attempts < this.maxPollingAttempts) {
					console.log(`查询失败，${this.pollingInterval}ms后重试`);
					this.pollingIntervals.set(orderId, setTimeout(poll, this.pollingInterval));
				} else {
					this.stopPolling(orderId);
					onFail && onFail(orderId, error);
				}
			}
		};
		
		// 开始轮询
		poll();
	}

	/**
	 * 停止轮询
	 * @param {string} orderId 订单ID
	 */
	stopPolling(orderId) {
		const interval = this.pollingIntervals.get(orderId);
		if (interval) {
			clearTimeout(interval);
			this.pollingIntervals.delete(orderId);
			console.log('停止轮询:', orderId);
		}
	}

	/**
	 * 停止所有轮询
	 */
	stopAllPolling() {
		this.pollingIntervals.forEach((interval, orderId) => {
			this.stopPolling(orderId);
		});
		console.log('已停止所有支付轮询');
	}

	/**
	 * 检查是否有活跃的轮询
	 * @returns {boolean}
	 */
	hasActivePolling() {
		return this.pollingIntervals.size > 0;
	}

	/**
	 * 获取活跃轮询数量
	 * @returns {number}
	 */
	getActivePollingCount() {
		return this.pollingIntervals.size;
	}

	/**
	 * 完整的支付流程
	 * @param {Object} orderData 订单数据
	 * @param {Function} onSuccess 支付成功回调
	 * @param {Function} onFail 支付失败回调
	 * @param {Function} onTimeout 支付超时回调
	 */
	async processPayment(orderData, onSuccess, onFail, onTimeout) {
		try {
			console.log('开始支付流程，订单数据:', orderData);
			
			// 1. 创建订单并获取支付参数
			const { order, payParams } = await this.createOrderAndGetPayment(orderData);
			console.log('订单创建成功:', order);
			
			// 2. 调起微信支付
			await this.callWechatPay(payParams);
			console.log('微信支付调用成功');
			
			// 3. 开始轮询支付状态
			this.startPaymentPolling(
				order._id,
				onSuccess,
				onFail,
				onTimeout
			);
			
			return order;
		} catch (error) {
			console.error('支付流程失败:', error);
			onFail && onFail(null, error);
			throw error;
		}
	}
}

export default RepairServicePayment; 